package com.darker.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.darker.yygh.cmn.config.DictListener;
import com.darker.yygh.cmn.mapper.DictMapper;
import com.darker.yygh.cmn.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    DictMapper dictMapper;

    //根据ID取子数据
    @Cacheable(value = "dict",keyGenerator = "keyGenerator" )
    @Override
    public List<Dict> findChildData(Long id) {
//        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Dict::getParentId, id);
        List<Dict> dictlist = dictMapper.list(id);
        //设置数据中有没有子数据
        for (Dict dict : dictlist) {
            Long dictId = dict.getId();
            boolean flag = findChild(dictId);
            dict.setHasChildren(flag);
        }

        return dictlist;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictEeVos = new ArrayList<>();
        DictEeVo dictEeVo;
        for (Dict dict : dictList) {
            dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVos.add(dictEeVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    @CacheEvict(value = "dict",allEntries = true)//清空redis缓存
    @Override
    //导入表格数据
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class
                    ,new DictListener(dictMapper)).
                    sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //根据dictcode和value查询
    @Override
    public String getDictName(String dictCode, String value) {

            LambdaQueryWrapper<Dict> lambdaQueryWrapper=new LambdaQueryWrapper<>();
             //dictCode为空 根据value
            if(StringUtils.isEmpty(dictCode)){
                lambdaQueryWrapper.eq(Dict::getValue,value);
                Dict dict = dictMapper.selectOne(lambdaQueryWrapper);
                return dict.getName();
            }
            else {
                //dictCode不为空 根据dictCode,value
                Dict fatherDict= this.getDictByDictCode(dictCode);
                Long parentId = fatherDict.getId();

                lambdaQueryWrapper.eq(Dict::getValue,value)
                        .eq(Dict::getParentId,parentId);
                Dict parentDict =dictMapper.selectOne(lambdaQueryWrapper);
                return parentDict.getName();
            }

    }
    //根据dictCode查询
    public Dict getDictByDictCode(String dictCode){
        LambdaQueryWrapper<Dict> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getDictCode,dictCode);
        Dict dict= dictMapper.selectOne(lambdaQueryWrapper);
        return dict;
    }

    //    根据dictCode获取下级节点
    @Override
    public List<Dict> findBydictCode(String dictCode) {
        //根据dictCode查Id
        Dict dict = this.getDictByDictCode(dictCode);
        Long id = dict.getId();
        //根据id查数据
        List<Dict> childData = this.findChildData(id);
        return childData;
    }


    //判断数据中有没有中数据
    private boolean findChild(Long id) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId, id);
        int count = this.count(lambdaQueryWrapper);
        return count > 0;
    }
}
